package com.zzg.lucene.index;

import java.io.IOException;
import java.nio.file.Paths;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.springframework.util.StringUtils;

public class LuceneIndex {
	private String[] ids = { "1", "2" };
	private String[] unIndex = { "Netherlands", "Italy" };
	private String[] unStored = { "Amsterdam has lots of bridges", "Venice has lots of canals" };
	private String[] text = { "Amsterdam", "Venice" };

	/**
	 * 创建索引写入器
	 *
	 * @param indexPath
	 * @param create
	 * @throws IOException
	 */
	public IndexWriter getIndexWriter(String indexPath, boolean create) throws IOException {
		Directory directory = null;
		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new StandardAnalyzer());
		if (create) {
			indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
		} else {
			indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
		}
		
		if(StringUtils.isEmpty(indexPath)){
			directory =  new RAMDirectory();
		} else{
			directory = FSDirectory.open(Paths.get(indexPath));
		}
		
		IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
		return indexWriter;
	}
	
	public void createIndex() throws IOException {
		IndexWriter indexWriter = getIndexWriter("C:\\lucene\\index",false);
        for (int i = 0; i < ids.length; i++) {
            Document document = new Document();
            document.add(new StringField("id", ids[i], Store.YES));
            document.add(new StringField("country", unIndex[i], Store.YES));
            document.add(new TextField("contents", unStored[i], Store.YES));
            document.add(new TextField("city", text[i], Store.YES));
            indexWriter.addDocument(document);
        }
        indexWriter.commit();
    }

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		LuceneIndex index = new LuceneIndex();
		index.createIndex();
		System.out.println("内存索引创建成功");
	}

}
